package com.neu.questionnaire_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neu.questionnaire_system.beans.ResponseEntity;
import com.neu.questionnaire_system.entity.Questionnaire;
import com.neu.questionnaire_system.entity.Tenant;
import com.neu.questionnaire_system.mapper.*;
import com.neu.questionnaire_system.service.TenantService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neu.questionnaire_system.util.Constants;
import com.neu.questionnaire_system.util.EmailSender;
import com.neu.questionnaire_system.util.UUIDGenerator;
import org.apache.commons.mail.EmailException;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xingle
 * @since 2022-10-31
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements TenantService {
    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private QuestionnaireMapper questionnaireMapper;
;

    public ResponseEntity insertTenant(String tenantName, String id, String password, String phone){
        String tid = UUIDGenerator.getOneUUID();
        String isDeleted = "0";
        double fee=charge(tid);
        int res = tenantMapper.insertTenant(tenantName,tid,id,fee,password,phone,isDeleted);
        ResponseEntity re = new ResponseEntity();
        re.setData(res);
        if(res > 0){
            re.setMessage(Constants.ADD_MESSAGE);
            re.setCode(Constants.SUCCESS_CODE);
        }else{
            re.setMessage(Constants.ADD_FAIL_MESSAGE);
            re.setCode(Constants.FAIL_CODE);
        }
        return re;
    }

    /**
     * 计费 jyh
     *
     */

    double charge(String tid){
        double fee=0.0;
        double clusterFee=tenantMapper.ClusterFee(tid)*1;
        double questionnaireFee=tenantMapper.QuestionnaireFee(tid)*0.5;
        int answeredCount=0;
        //System.out.println(clusterFee+" "+questionnaireFee*2+" "+tid+" "+tenantMapper.AnswerFee(tid));
        List<String>uid=tenantMapper.uidInTid(tid);

        //int answer=questionnaireMapper.findAnsweredCountByUid("05eddee471864b00948f9a0b71f5623c");
        //System.out.println(answer);
        List<Integer> list = tenantMapper.AnswerFee(tid);
        for(int i=0;i<list.size();i++){
            System.out.println(list.get(i));
            answeredCount=answeredCount+list.get(i);
        }
        double answerFee=answeredCount*0.1;
        fee=clusterFee+questionnaireFee+answerFee;
        return fee;
    }




    /**
     * 展示所有租户
     * @return 返回包含分页信息的对象
     */
    public ResponseEntity showTenant(){
        ResponseEntity responseEntity = new ResponseEntity();
        List<IPage<Tenant>> list = new ArrayList<>();
        int current = 1;
        long count = 0;
        fee();
        while (count<=tenantMapper.selectCount(null)){
            IPage<Tenant> iPage = tenantMapper.showTenant(new Page<>(current,Constants.PAGE_SIZE));

            list.add(iPage);
            current++;
            count += iPage.getSize();
        }

        responseEntity.setData(list);
        responseEntity.setMessage(Constants.SELECT_MESSAGE);
        responseEntity.setCode(Constants.SUCCESS_CODE);
        return responseEntity;
    }

    public void fee(){
        List<String> list=tenantMapper.findAllTid();
        for (String s:list
             ) {
            double fee = charge(s);
            int a=tenantMapper.updateFeeById(fee,s);
        }
    }

    /**
     * created by libo 租户删除重构，实现逻辑删除，系统保留曾经记录，同时加入判断租户下是否有用户
     * @param tid 需要删除租户的tid
     * @return 返回统一的对象
     */
    public ResponseEntity deleteTenant(String tid){
        ResponseEntity responseEntity = new ResponseEntity();
        if (userMapper.queryUserByTid(tid)>0){
            responseEntity.setCode(Constants.FAIL_CODE);
            responseEntity.setMessage(Constants.TENANT_FAIL_DELETE_MESSAGE);
        }else {
            int res = tenantMapper.deleteTenantByTrue(tid);
            if(res > 0){
                responseEntity.setMessage(Constants.DELETE_MESSAGE);
                responseEntity.setCode(Constants.SUCCESS_CODE);
                responseEntity.setData(res);
            }else{
                responseEntity.setMessage(Constants.DELETE_FAIL_MESSAGE);
                responseEntity.setCode(Constants.FAIL_CODE);
            }
        }
        return responseEntity;
    }

    public ResponseEntity findTenantById(String tid){
        ResponseEntity re = new ResponseEntity();
        List<Tenant> res = tenantMapper.findTenantById(tid);
        re.setData(res);
        if(res !=null){
            re.setMessage(Constants.SELECT_MESSAGE);
            re.setCode(Constants.SUCCESS_CODE);
        }else{
            re.setMessage(Constants.SELECT_FAIL_MESSAGE);
            re.setCode(Constants.FAIL_CODE);
        }
        return re;
    }

    public ResponseEntity updateTenantById(String tid,String tenantName,String password,String phone){
        int res = tenantMapper.updateTenantById(tid,tenantName,password,phone);
        ResponseEntity re = new ResponseEntity();
        re.setData(res);
        if(res > 0){
            re.setMessage(Constants.UPDATE_MESSAGE);
            re.setCode(Constants.SUCCESS_CODE);
        }else{
            re.setMessage(Constants.UPDATE_FAIL_MESSAGE);
            re.setCode(Constants.FAIL_CODE);
        }
        return re;
    }

    public ResponseEntity login(String tenantName,String password){
        QueryWrapper<Tenant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tenantName",tenantName);
        queryWrapper.eq("password",password);
        int res = tenantMapper.selectCount(queryWrapper);
        ResponseEntity re = new ResponseEntity();
        if(res > 0){
            re.setMessage(Constants.LOGIN_SUCCESS_MESSAGE);
            re.setCode(Constants.SUCCESS_CODE);
            re.setData(tenantMapper.selectOne(queryWrapper));
        }else{
            re.setMessage(Constants.LOGIN_FAIL_MESSAGE);
            re.setCode(Constants.FAIL_CODE);
        }
        return re;
    }

    public ResponseEntity sendTenantEmail(Map<String,Object> map) throws EmailException {
        ResponseEntity responseEntity = new ResponseEntity();
        String email = (String)map.get("email");
        String code = (String)map.get("code");
        EmailSender.simpleEmailSend(code,email);
        responseEntity.setData(1);
        responseEntity.setMessage(Constants.SEND_MESSAGE);
        responseEntity.setCode(Constants.SUCCESS_CODE);
        return responseEntity;
    }

    public ResponseEntity findTenantByName(String tenantName){
        ResponseEntity re = new ResponseEntity();
        tenantName = "%" + tenantName + "%";
        List<Tenant> res = tenantMapper.findTenantByName(tenantName);
        re.setData(res);
        if(res !=null){
            re.setMessage(Constants.SELECT_MESSAGE);
            re.setCode(Constants.SUCCESS_CODE);
        }else{
            re.setMessage(Constants.SELECT_FAIL_MESSAGE);
            re.setCode(Constants.FAIL_CODE);
        }
        return re;
    }

    public ResponseEntity deleteTenantByName(String tenantName){
        ResponseEntity response = new ResponseEntity();
        int result = tenantMapper.deleteTenantByName(tenantName);
        response.setData(result);
        if(result > 0){
            response.setMessage(Constants.DELETE_MESSAGE);
            response.setCode(Constants.SUCCESS_CODE);
        }else{
            response.setMessage(Constants.DELETE_FAIL_MESSAGE);
            response.setCode(Constants.FAIL_CODE);
        }
        return response;
    }

    public ResponseEntity updateTenantByName(String oldTenantName, String newTenantName, String password, String phone){
        ResponseEntity response = new ResponseEntity();
        int result = tenantMapper.updateTenantByName(oldTenantName,newTenantName,password,phone);
        response.setData(result);
        if(result > 0){
            response.setMessage(Constants.UPDATE_MESSAGE);
            response.setCode(Constants.SUCCESS_CODE);
        }else{
            response.setMessage(Constants.UPDATE_FAIL_MESSAGE);
            response.setCode(Constants.FAIL_CODE);
        }
        return response;
    }

    public ResponseEntity TenantStatistic(){
        ResponseEntity responseEntity = new ResponseEntity();
        List<Map<String,Object>> list = tenantMapper.tenantStatistic();
        responseEntity.setData(list);
        responseEntity.setMessage(Constants.SELECT_MESSAGE);
        responseEntity.setCode(Constants.SUCCESS_CODE);
        return responseEntity;
    }



}
